package com.tom.happy.mrs.chicken;

import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.tom.happy.mrs.chicken.view.CountDownView;

import java.util.ArrayList;

public class ChickenCoopFragment extends BaseFragment {
    private CountDownView mCountDownView;
    private ImageView yHouse;
    private ImageView bHouse;
    private Rect yHouseRect;
    private Rect bHouseRect;
    private Rect mTmpRect = new Rect();
    private int[] mTmpLoc = new int[2];

    // 不可下蛋的高度, 上半部分不能下蛋.
    private int mUnLayHeight;
    // 母鸡随机下蛋, 可下蛋的位置;
    private int mLines, mColumns;

    private int mMaxEggs = 5;

    private ArrayList<Integer> mPosList = new ArrayList<Integer>(mMaxEggs);

    // 母鸡的默认位置
    private float mMotherPosX, mMotherPosY;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLayoutResID = com.tom.happy.mrs.chicken.R.layout.fragment_chicken_coop;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        yHouse = (ImageView) mLayoutView.findViewById(com.tom.happy.mrs.chicken.R.id.y_house);
        bHouse = (ImageView) mLayoutView.findViewById(com.tom.happy.mrs.chicken.R.id.b_house);
        mCountDownView = (CountDownView) mLayoutView.findViewById(com.tom.happy.mrs.chicken.R.id.countDownView);

        switch (mGameType) {
            case GAME_TYPE_COOP_ONE:
                bHouse.setVisibility(View.GONE);
                mCountDownView.setVisibility(View.GONE);
                break;
            case GAME_TYPE_COOP_ONE_COUNTER:
                bHouse.setVisibility(View.GONE);
                break;
            case GAME_TYPE_COOP_TWO:
                mCountDownView.setVisibility(View.GONE);
                break;
            case GAME_TYPE_COOP_TWO_COUNTER:
                break;
        }

        mUnLayHeight = mDisplayHeight / 2;
        // 右边有退出的门
        mColumns = (mDisplayWidth - 100) / mEggWidth;
        mLines = (mDisplayHeight - mUnLayHeight) / mEggWidth;

        ImageButton quitView = (ImageButton) mLayoutView.findViewById(com.tom.happy.mrs.chicken.R.id.quit);
        ((AnimationDrawable) quitView.getBackground()).start();

        mMother.post(new Runnable() {
            @Override
            public void run() {
                mMotherPosX = mMother.getX();
                mMotherPosY = mMother.getY();
            }
        });
        return mLayoutView;
    }

    @Override
    public void onResume() {
        super.onResume();
        startGame();
        if (mCountDownView.getVisibility() == View.VISIBLE) {
            mCountDownView.start();
        }
    }

    private void startGame() {
        if (mCurrentChickens == 0) {
            randomLayEgg();
        }
    }

    private void randomLayEgg() {
        // 1. 计算蛋的位置.
        int pos[] = choosePlace();
        // 2. 移动母鸡到指定位置, 移动结束后动画下蛋.
        int x = pos[0] - (mMotherWidth - mEggWidth) / 2;
        // 母鸡与鸡蛋底部对齐
        int y = pos[1] - (mMotherWidth - mEggWidth);
        Message msg = mHandler.obtainMessage(MSG_MOVE_TO_POS);
        msg.arg1 = x;
        msg.arg2 = y;
        mHandler.sendMessage(msg);
    }

    /**
     * 随机选择一个可下蛋位置
     */
    private int[] choosePlace() {
        int index = mRandom.nextInt(mColumns * mLines - 1);
        int count = 0;
        while (mPosList.contains(index)) {
            index = mRandom.nextInt(mColumns * mLines - 1);
        }
        mPosList.add(index);
        if (mPosList.size() >= mMaxEggs) {
            mPosList.clear();
        }

        int x = (index % mColumns) * mEggWidth;
        int y = mUnLayHeight + (index / mColumns) * mEggWidth;

        return new int[]{x, y};
    }

    @Override
    protected View.OnTouchListener getTouchListener() {
        return mOnTouchListener;
    }

    View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        float oriX = 0;
        float oriY = 0;
        boolean isYellow;
        float offsetX, offsetY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (!(v instanceof ImageView)) {
                return false;
            }
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    oriX = view.getX();
                    oriY = view.getY();
                    offsetX = event.getRawX() - oriX;
                    offsetY = event.getRawY() - oriY;
                    isYellow = mEggColorMaps.get(view);
                    break;
                case MotionEvent.ACTION_MOVE:
                    // 拖动小鸡, 清除小鸡离开动画.
                    cancelChickenLeaveAnim(view);
                    float preX = view.getX();
                    view.setX(event.getRawX() - offsetX);
                    view.setY(event.getRawY() - offsetY);
                    ImageView tartHouse = isYellow ? yHouse : bHouse;
                    // 正确的小屋闪动.
                    if (chickenCanIn(view, isYellow)) {
                        if (tartHouse.getAnimation() == null || !tartHouse.getAnimation().hasStarted()) {
                            animTheHouse(tartHouse);
                        }
                    } else {
                        if (tartHouse.getAnimation() != null) {
                            tartHouse.getAnimation().cancel();
                        }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    // 到达正确的小屋
                    if (chickenCanIn(view, isYellow)) {
                        hideChicken(view);
                        mCatchCount++;
                        mCatchCountView.setText("" + mCatchCount);
                    } else {
                        moveChickenToOriPos(view, oriX, oriY);
                    }
                    break;
            }

            return true;
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeMessages(MSG_PLAY_CHICKEN_RING);
        mSoundPool.autoPause();
    }

    private void animTheHouse(ImageView house) {
        ObjectAnimator animator = ObjectAnimator.ofObject(house, View.TRANSLATION_Y.getName(),
                new IntEvaluator(), -15, 15, 0);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.setInterpolator(new BounceInterpolator());
        animator.start();
    }

    private boolean chickenCanIn(View view, boolean isYellow) {
        ImageView targetHouse = isYellow ? yHouse : bHouse;
        Rect targetRect = isYellow ? yHouseRect : bHouseRect;
        if (targetRect == null) {
            targetHouse.getLocationOnScreen(mTmpLoc);
            targetRect = new Rect(mTmpLoc[0], mTmpLoc[1], mTmpLoc[0] + targetHouse.getWidth(), mTmpLoc[1] + targetHouse.getHeight());
        }

        view.getLocationOnScreen(mTmpLoc);
        mTmpRect.set(mTmpLoc[0], mTmpLoc[1], mTmpLoc[0] + view.getWidth(), mTmpLoc[1] + view.getHeight());
        return targetRect.intersect(mTmpRect);
    }

    @Override
    protected void hideChicken(ImageView view) {
        super.hideChicken(view);
        if (mCurrentChickens <= 0) {
            randomLayEgg();
        }
    }

    @Override
    public void onMotherAnimEnd() {
        if (mCurrentChickens < mMaxEggs) {
            randomLayEgg();
        } else {
            moveMotherToPos(mMother, mMotherPosX, mMotherPosY, false);
        }
    }
}
